package com.lehezn.opensource.appkit.ControlModule;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.lehezn.opensource.appkit.R;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * Created by es-ll on 17/10/22.
 */

public class AddEleActivity extends GosControlModuleBaseActivity {
    private EditText etName, etAddr;
    private Spinner spType, spBuard, spJiaoyan, spChannel;
    private Switch switchIsSanxiang, switchIsSupportFenggu;
    byte type = 0;
    byte buard = 1;
    byte jiaoyan = 0;
    int chnnel = 0;
    boolean isSanxiang, isSupportFenggu=true;
    public static MeterInfo meterInfo;

    private byte action = Util.ACTION_ADD;

//    private GizWifiDevice gizWifiDevice;

    private Button btnSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a_add);
        initDevice();
        initView();
        setActionBar(true, true, "添加表");
//        updateUi();
        addListener();

    }

    //    private void initDevice() {
//        Intent intent = getIntent();
//        mDevice = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice");
//        mDevice.setListener(gizWifiDeviceListener);
//        Log.i("Apptest", mDevice.getDid());
//    }
    private void initDevice() {
        Intent intent = getIntent();
        device = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice");
        action = intent.getByteExtra("action", Util.ACTION_ADD);

    }


    private void addListener() {
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                type = Util.convertSpinnerToByte((byte) i);

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        spBuard.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                buard = (byte) i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        spJiaoyan.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                jiaoyan = (byte) i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        spChannel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                chnnel = (byte) i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        switchIsSanxiang.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isSanxiang = b;
            }
        });
        switchIsSupportFenggu.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isSupportFenggu = b;
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int addrLen = 0;
                try {
                    addrLen = etAddr.getText().toString().getBytes("utf-8").length;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
//                if (addrLen < 12 || addrLen > 14) {
//                    Toast.makeText(AddEleActivity.this, "地址长度不正确", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                try {
                    if (etName.getText().toString().getBytes("utf-8").length >= 16) {
                        Toast.makeText(AddEleActivity.this, "名字太长了", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                byte[] data = add();
                MyLog.d("addBytes===>"+Util.bytesToHexString(data));
                sendJson("meter_info", data);
                finish();
            }
        });


    }

    private void initView() {
        etName = (EditText) findViewById(R.id.et_name);

        etAddr = (EditText) findViewById(R.id.et_addr);


        spType = (Spinner) findViewById(R.id.spinner_type);
        spBuard = (Spinner) findViewById(R.id.spinner_buard);
        spJiaoyan = (Spinner) findViewById(R.id.spinner_jiaoyan);
        spChannel = (Spinner) findViewById(R.id.spinner_channel);

        switchIsSanxiang = (Switch) findViewById(R.id.switch_sanxiang);
        switchIsSupportFenggu = (Switch) findViewById(R.id.switch_fenggu);

        btnSave = (Button) findViewById(R.id.button_save);

        if (action == Util.ACTION_MODIFY && meterInfo != null) {
            etName.setText(meterInfo.name);
            String addrStr=meterInfo.addrStr;
            if (meterInfo.type==Util.TYPE_SINGLE_METER||meterInfo.type==Util.TYPE_MUTIL_METER){
                addrStr=meterInfo.addrStr;
            }

            etAddr.setText(addrStr.replace(" ", ""));//去掉空格
            spType.setSelection(Util.convertTypeToSpinnerPos(meterInfo.type));
            spBuard.setSelection(meterInfo.baud);
            switchIsSupportFenggu.setSelected(meterInfo.isPeakvall);
            spChannel.setSelection(meterInfo.channel);


        }


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.saves:
                int addrLen = 0;
                try {
                    addrLen = etAddr.getText().toString().getBytes("utf-8").length;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
//                if (addrLen < 12 || addrLen > 14) {
//                    Toast.makeText(AddEleActivity.this, "地址长度不正确", Toast.LENGTH_SHORT).show();
//                    return super.onOptionsItemSelected(item);
//                }
                try {
                    if (etName.getText().toString().getBytes("utf-8").length >= 16) {
                        Toast.makeText(AddEleActivity.this, "名字太长了", Toast.LENGTH_SHORT).show();
                        return super.onOptionsItemSelected(item);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                byte[] data = add();
                MyLog.d("addBytes===>"+Util.bytesToHexString(data));
                sendJson("meter_info", data);
                finish();



                break;

            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }
    /**
     * 表信息：表数量1B+执行1B+地址7B+表类型1B+波特率1B+峰谷1B+通道1B+名称16B，最多16个表（27B *8+1=217B）
     */
    private byte[] add() {

        ByteBuffer byteBuffer = ByteBuffer.allocate(31);

        byte len = 1;
        byteBuffer.put(len);

        byteBuffer.put(action);

        ByteBuffer byteBufferAddr = ByteBuffer.allocate(7);

//        if (type==Util.TYPE_SINGLE_METER||type==Util.TYPE_MUTIL_METER){
//            byteBufferAddr.put((byte) 0);
//        }
        byteBufferAddr.put(Util.hexStringToByte(etAddr.getText().toString()));
        byteBuffer.put(Util.revertOrder(byteBufferAddr.array()));
        byteBuffer.put(type);
        byteBuffer.put(buard);
//        byteBuffer.put(jiaoyan);
//        byteBuffer.put(isSanxiang? (byte)0:1);//// TODO: 17/10/5 type中可以表示单三项
//        byteBuffer.put(isSupportFenggu ? (byte) 0 : 1);
//        byteBuffer.put((byte) chnnel);
        String mix = "00000" + ((chnnel == 2) ? "10" : "0" + chnnel) + "" + (isSupportFenggu ? (byte) 0 : 1);
        byteBuffer.put((byte) Integer.parseInt(mix, 2));

        ByteBuffer byteBufferName = ByteBuffer.allocate(16);
        byte nameLen = 0 ;
        try {
            nameLen = (byte) etName.getText().toString().getBytes("utf-8").length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byteBufferName.put(nameLen);
        try {
            byteBufferName.put(etName.getText().toString().getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byteBuffer.put(byteBufferName.array());


        return byteBuffer.array();
    }


}
